#include "bluetooth.h"                                                           //Check and edit it
#include "bldc_foc.h"
Bluetooth_DataFrame Bluetooth_DataBuffer;
unsigned char * Buffer_Array = (unsigned char*)(&Bluetooth_DataBuffer);
unsigned char * Device_Data  = (unsigned char*)(&BluetoothData);
unsigned short bt_RecData;
void _Bluetooth_SendData(USART_Device *device, Bluetooth_DataFrame *data, int buffer_size)
{
    unsigned char * buffer = (unsigned char *)data;
    for(int i = 0; i < buffer_size; i++){
        while(!USART_GetFlagStatus(HT_USART1, USART_FLAG_TXC));
        _USART_SENDDATA(buffer[i]);
    }
}

void UART1_IRQHandler(void)
{
    bt_RecData = _USART_RECIEVEDATA(BLUETOOTH_NAME);
    bt_RecData |= (0x01 << 15);
    Bluetooth_DataHandler(&bt_RecData);
}

int Bluetooth_DataHandler(unsigned short *Data)
{
    unsigned short RecData;
    *Data &= (~(0x01 << 15));
    RecData = *Data;
    static int data_ready = 0;
    if(data_ready){
        if(data_ready == BUFFER_SIZE-1){
            if(RecData == FRAME_END){
                Buffer_Array[data_ready] = RecData;
                data_ready = 0;
                for(int i = 0;i<BUFFER_SIZE; i++){
                    Device_Data[i] = Buffer_Array[i];
                }
                *Data |= (0x01 << 14);
            }
            else{
                for(int i=0; i<BUFFER_SIZE-1; i++){
                    Buffer_Array[i] = 0;
                }
                data_ready = 0;
            }
        }
        else if(data_ready < BUFFER_SIZE){
            Buffer_Array[data_ready++] = RecData;
        }
        else{
            for(int i=0; i<BUFFER_SIZE; i++){
                    Buffer_Array[i] = 0;
            }
            data_ready = 0;
        }
    }
    else {
        switch(RecData)
        {
            case FRAME_HEAD:Buffer_Array[data_ready++] = RecData;break;
            case 0x0D      :
                BluetoothData.FreeFlag = 1;break;
            default        :
                data_ready = 0;break;
        }
    }

    return 0;
}

